import store from 'store';
import { showLoadingbar } from 'shared/actions/loadingBar';

class PromiseCounter {
  static count = 0;

  static countUp() {
    PromiseCounter.count = Math.max(PromiseCounter.count + 1, 0);
  }

  static countDown() {
    PromiseCounter.count = Math.max(PromiseCounter.count - 1, 0);
  }

  static reset() {
    PromiseCounter.count = 0;
  }

  static isEmpty() {
    return PromiseCounter.count === 0;
  }
}

export const showLoading = () => {
  if (PromiseCounter.isEmpty()) {
    store.dispatch(showLoadingbar(true));
  }
  PromiseCounter.countUp();
};

export const hideLoading = () => {
  setTimeout(() => {
    PromiseCounter.countDown();
    if (PromiseCounter.isEmpty()) {
      store.dispatch(showLoadingbar(false));
    }
  }, 0);
};